package com.mdnote.structure.search;

import java.util.Arrays;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/28
 * @description 斐波那契查找
 */
public class FabonacciSearch {

    private static final int fabonacciArraySize = 20;

    /**
     * 创建斐波那契数列
     * [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
     */

    private static int[] fabonacciArray = generateFabonacci();

    public static int search(int[] source, int element) {

        // 拿到source的长度，b表示元素组的大小对应到斐波那契数组的值
        int k = 0;
        for (int i = 0; i < fabonacciArray.length; i++) {
            if (fabonacciArray[i] >= source.length) {
                k = i;
                break;
            }
        }
        // 把原来的数组扩展至k，用最后一个数填充
        int[] temp = Arrays.copyOf(source, fabonacciArray[k]);
        for (int i = source.length; i < fabonacciArray[k]; i++) {
            temp[i] = source[source.length - 1];
        }

        // 按照斐波那契分割
        while (k > 0) {
            // 获取中间值
            int mid = fabonacciArray[k - 2];
            if (element < temp[mid]) {
                // 在左边
                k -= 2;
            } else if (element > temp[mid]) {
                // 在右边
                k--;
            } else {
                // 找到了
                return mid;
            }
        }
        return -1;
    }

    private static int[] generateFabonacci() {
        int[] fabonacciArray = new int[fabonacciArraySize];
        fabonacciArray[0] = 1;
        fabonacciArray[1] = 1;
        for (int i = 2; i < fabonacciArraySize; i++) {
            fabonacciArray[i] = fabonacciArray[i - 1] + fabonacciArray[i - 2];
        }
        return fabonacciArray;
    }

    public static void main(String[] args) {
        int[] data = new int[]{11, 22, 33, 44, 66, 88};
        System.out.println(search(data, 44));
    }
}
